<template>
  <edit-dialog :centerDialogVisible="visible" :tilte="title" width="960" @Cancel="handleCancel"  :defaultButton="false">
    <template #content>
      <el-form ref="formRef" label-width="130" :model="form" :rules="rules" style="width: 100%">
        <el-row>
          <el-col :span="12"> 
            <el-form-item label="事件名称：">
              <span>{{ form.eventName }}</span>
            </el-form-item>
            <el-form-item label="发生地点：">
              <span>{{ form.occurPlace }}</span>
            </el-form-item>
            <el-form-item v-if="type==='detail'" label="区域处置单位：">
              <span >{{ form.processGroup.name }}</span>
            </el-form-item>
            <el-form-item v-else label="区域处置单位：" prop="unit">
              <el-tree-select ref="unitRef" v-model="form.unit" :data="treeData" node-key="organizationId"
                          placeholder="请选择" show-checkbox check-strictly :props="{label: 'organizationName'}"
                          @change="unitTreeChange"/>
            </el-form-item>
            <el-form-item v-if="type==='detail'" label="电话：">
              <span >{{ form.headTel }}</span>
            </el-form-item>
            <el-form-item v-else label="电话：" prop="headTel">
              <el-input placeholder="请输入" v-model="form.headTel">
              </el-input>
            </el-form-item>
            <el-form-item v-if="type==='detail'" label="事件状态：">
              <span >{{ dicFormatter(props.options.evenStatusOptions,form.eventStatus) }}</span>
            </el-form-item>
            <el-form-item v-else label="事件状态：" prop="eventStatus">
              <el-radio-group v-model="form.eventStatus">
                <el-radio  :key="1" :label="1">处置中</el-radio>
                <el-radio  :key="2" :label="2">已完结</el-radio>
              </el-radio-group>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="发生时间：">
              <span>{{ form.createTime }}</span>
            </el-form-item>
            <el-form-item label="类型：">
              <span>普通事件</span>
            </el-form-item>
            <el-form-item v-if="type==='detail'" label="事件负责人：">
              <span >{{ form.eventHeadName}}</span>
            </el-form-item>
            <el-form-item v-else label="事件负责人：" prop="eventHead">
              <!-- <el-input placeholder="请输入" v-model="form.eventHead"></el-input> -->
              <el-select v-model="form.eventHead" placeholder="请选择" @change="eventHeadChange">
                <el-option
                  v-for="item in peopleOption"
                  :key="item.value"
                  :label="item.label"
                  :value="item.value">
                </el-option>
              </el-select>
            </el-form-item>
           
            <el-form-item v-if="type==='detail'" label="事件类型：">
              <span>{{ dicFormatter(props.options.eventTypeOptions,form.eventTypeId) }}</span>
            </el-form-item>
            <el-form-item v-else label="事件类型：" prop="eventTypeId">
              <el-select v-model="form.eventTypeId" placeholder="请选择" style="width: 100%;">
                <el-option
                  v-for="item in props.options.eventTypeOptions"
                  :key="item.value"
                  :label="item.label"
                  :value="item.value">
                </el-option>
              </el-select>
            </el-form-item>
          </el-col>
        </el-row>
        <div>
          <el-form-item  v-if="type==='detail'" label="简要经过：">
            <span>{{ form.eventProcess }}</span>
          </el-form-item>
          <el-form-item  v-else label="简要经过：" prop="eventProcess">
            <el-input placeholder="请输入" v-model="form.eventProcess"></el-input>
          </el-form-item>
        </div>
        <div>
          <el-form-item v-if="type==='detail'" label="处理情况：">
            <span>{{ form.eventHandle }}</span>
          </el-form-item>
          <el-form-item v-else label="处理情况：" prop="eventHandle">
            <el-input placeholder="请输入" v-model="form.eventHandle"></el-input>
          </el-form-item>
        </div>
        <div>
          <el-form-item v-if="type==='detail'" label="采取措施：">
            <span>{{ form.eventMeasure }}</span>
          </el-form-item>
          <el-form-item  v-else label="采取措施：" prop="eventMeasure">
            <el-input placeholder="请输入" v-model="form.eventMeasure">
            </el-input>
          </el-form-item>
        </div>
      </el-form>
    </template>
    <template #custom>
      <div v-if="type==='detail'">
        <el-button @click="handleCancel">关闭</el-button>
      </div>
      <div v-else>
        <el-button @click="handleCancel">取消</el-button>
        <el-button type="primary" @click="onSubmit" :loading="submitLoading" :disabled="submitLoading">保存</el-button>
      </div>
    </template>
  </edit-dialog>
</template>

<script lang="ts" setup>
import { eventFill } from '@/api/event/record'
import { reactive, ref } from "vue";
import EditDialog from "../../components/modal.vue";
import dicFormatter from '@/hooks/commonUtil'
import {useStore} from "vuex";
import { ElMessage } from 'element-plus'
import { getUserInfo } from "@/api/eqpt/houseManger";

const emit = defineEmits(['success']);
const props = defineProps({
  options:{
    type: Object,
    default: {}
  }
})
const store = useStore()
const userInfo = store.state.user.userInfo;
const tree = store.getters['user/getAllOrganTree']
const treeData=ref(tree);
// const userList = ref([])
// function getAllPeople(){
//   getUserInfo({}).then((res:any)=>{
//     userList.value=res.data.map((item:any)=>{
//       return {
//         value: item.userId,
//         label: item.name
//       }
//     })
//   })
// }
// getAllPeople()

const type = ref('detail');
const title = ref('查看事件');
const visible = ref(false);
const formRef = ref();
const form:any = reactive({
  id: '',
  eventName: '',
  createTime: '',
  // eventType1: '', 
  occurPlace: '',
  eventHead: '', // 事件负责人id
  eventHeadName: '',
  headTel: '',
  eventStatus: undefined,
  eventTypeId: undefined,
  eventProcess:'',
  eventHandle:'',
  eventMeasure:'',
  eventType:'',
  unit:'',
  processGroup: {}
})
const rules = {
  unit: [
    {required: true, message: '请选择', trigger: ['blur', 'change']}
  ],
  eventHead: [
    {required: true, message: '请选择', trigger: ['blur', 'change']}
  ],
  headTel: [
    {required: true, message: '请输入', trigger: ['blur', 'change']},
    {pattern: /^1[34578]\d{9}$/, message: "请输入合法手机号", trigger: ['blur', 'change']},
  ],
  eventStatus: [
    {required: true, message: '请选择', trigger: ['blur', 'change']}
  ],
  eventType: [
    {required: true, message: '请选择', trigger: ['blur', 'change']}
  ],
  eventProcess: [
    {required: true, message: '请输入', trigger: ['blur', 'change']}
  ],
  eventHandle: [
    {required: true, message: '请输入', trigger: ['blur', 'change']}
  ],
  eventMeasure:[
    {required: true, message: '请输入', trigger: ['blur', 'change']}
  ],
}

// 联动
const processGroup = reactive({
  id:'',
  name: ''
})
const peopleOption=ref<{value:string,label:string}[]>([])
const unitRef=ref();
function unitTreeChange(val:any) {
  form.eventHead=undefined
  let checkedNodes = unitRef.value.getCheckedNodes()
  if (checkedNodes.length) {
    processGroup.name=checkedNodes[0].organizationName;
    processGroup.id= checkedNodes[0].organizationId;
    getUserInfo({groupIds: [checkedNodes[0].organizationId]}).then(res => {
        peopleOption.value = res.data.map((item:any)=>{
          return {
            value:item.userId,
            label:item.name
          }
        })
    })
  }
} 

const submitLoading= ref(false);
function onSubmit(){
  formRef.value
  .validate()
  .then(async () => {
    submitLoading.value = true;
    // console.log(form,'klklklklk')
    eventFill({
        ...form,
        processGroup,
        mender:{
          id: userInfo.userId,
          name: userInfo.name,
          organId: userInfo.organId,
          organName: userInfo.organName,
        }
      }).then((res:any)=>{
        ElMessage.success('操作成功')
        emit('success');
        handleCancel()
      }).catch((err)=>{
        ElMessage.error(err?.message || '操作失败')
      }).finally(()=>{
        submitLoading.value = false;
      })
  })
  .catch((err:any)=>{
    console.log(err,'校验错误')
  })
}

function open(type1:any,row:any){
  type.value=type1;
  if(type1==='detail'){
    title.value='查看事件'
  }else{
    title.value='处置事件'
  }
  form.id=row.id;
  form.eventName=row.eventName;
  form.createTime=row.createTime;
  form.occurPlace= row.occurPlace;
  form.eventHead=row.eventHead; // 事件负责人id
  form.eventHeadName = row.eventHeadName;
  form.headTel=row.headTel;
  form.eventStatus=Number(row.eventStatus);
  form.eventTypeId=Number(row.eventTypeId);
  form.eventType=row.eventType;
  form.eventProcess=row.eventProcess;
  form.eventHandle=row.eventHandle;
  form.eventMeasure=row.eventMeasure;
  form.processGroup=row.processGroup; // 区域组织信息
  form.unit = row.processGroup.id;
  processGroup.id= row.processGroup.id;
  processGroup.name= row.processGroup.name;
  getUserInfo({groupIds: [ row.processGroup.id]}).then(res => {
        peopleOption.value = res.data.map((item:any)=>{
          return {
            value:item.userId,
            label:item.name
          }
        })
    })
  visible.value=true;
}
function handleCancel(){
  visible.value=false;
}
function eventHeadChange(val:string){
  const findItem = peopleOption.value.find((item:any)=>{
    return item.value===val
  })
  form.eventHeadName=findItem?.label
}
defineExpose({
  open,
});

</script>

<style lang="less" scoped>

</style>
